// License: http://www.codeplex.com/entlibcontrib/Project/License.aspx
// Author: Randy

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using EntLibContrib.Logging.TraceListeners;

#if !NUNIT
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
using TestIgnore = NUnit.Framework.IgnoreAttribute;
#endif

namespace EntLibContrib.Logging.UnitTests.TraceListeners
{
	[TestClass]
    public class NoGuidRollingFlatFileTraceListenerTest
	{
        private const byte maxInstances = 1;
        private const bool throwMax = true;
        private string fileNameWithoutExtension;
		private string fileName;
		private const string extension = ".log";
        private MockDateTimeProvider dateTimeProvider = new MockDateTimeProvider();
        private int fileCount = 0;

		[TestInitialize]
		public void SetUp()
		{
            fileCount++;
            fileNameWithoutExtension = "RollingFlatFileTraceListenerTest" + fileCount;
			fileName = fileNameWithoutExtension + extension;
		}

		[TestCleanup]
		public void TearDown()
		{
			foreach (string createdFileName in Directory.GetFiles(".", fileNameWithoutExtension + "*"))
			{
				File.Delete(createdFileName);
			}
		}

        [TestMethod, ExpectedException(typeof(LoggingMaxInstancesException))]
        public void ThrowMaxInstancesWrite()
        {
            using (FileStream fileStream = File.Open(this.fileName, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
            {
                using (NoGuidRollingFlatFileTraceListener traceListener
                    = new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
						maxInstances, throwMax, 10, "yyyy", NoGuidRollFileExistsBehavior.Overwrite, RollInterval.Day, 0))
                {
                    traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;
                    traceListener.Write("1234567890");
                }
            }
        }

        [TestMethod, ExpectedException(typeof(LoggingMaxInstancesException))]
        public void ThrowMaxInstancesRollingHelper()
        {
            using (FileStream fileStream = File.Open(this.fileName, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
            {
                using (NoGuidRollingFlatFileTraceListener traceListener
                    = new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
						maxInstances, throwMax, 10, "yyyy", NoGuidRollFileExistsBehavior.Overwrite, RollInterval.Day, 0))
                {
                    traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;
                    Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());
                }
            }
        }

        [TestMethod]
		public void ListenerForNewFileWillUseCreationDateToCalculateRollDate()
		{
            using (NoGuidRollingFlatFileTraceListener traceListener
				= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
					maxInstances, throwMax, 0, "yyyy", NoGuidRollFileExistsBehavior.Overwrite, RollInterval.Day, 0))
			{
				traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;

				Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

				Assert.AreEqual(traceListener.RollingHelper.CalculateNextRollDate(File.GetCreationTime(this.fileName)), traceListener.RollingHelper.NextRollDateTime);
				Assert.IsNull(traceListener.RollingHelper.CheckIsRollNecessary());
			}
		}

        [TestMethod]
		public void ListenerForExistingFileWillUseCreationDateToCalculateRollDate()
		{
			File.WriteAllText(this.fileName, "existing text");
			File.SetCreationTime(this.fileName, new DateTime(2000, 01, 01));

			using (NoGuidRollingFlatFileTraceListener traceListener
				= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
					maxInstances, throwMax, 0, "yyyy", NoGuidRollFileExistsBehavior.Overwrite, RollInterval.Day, 0))
			{
				traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;

				Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

				Assert.AreEqual(traceListener.RollingHelper.CalculateNextRollDate(File.GetCreationTime(this.fileName)), traceListener.RollingHelper.NextRollDateTime);
        // Very small time may elapse between each DateTime
        Assert.IsTrue(Math.Abs(
            (this.dateTimeProvider.CurrentDateTime - traceListener.RollingHelper.CheckIsRollNecessary())
            .Value.TotalSeconds) < 1.0);
      }
		}

		[TestMethod]
		public void WriterKeepsTally()
		{
			using (NoGuidRollingFlatFileTraceListener traceListener
				= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null, maxInstances, throwMax, 10, "yyyy", NoGuidRollFileExistsBehavior.Overwrite, RollInterval.Day, 0))
			{
				traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;

				Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

				traceListener.Write("12345");

				Assert.AreEqual(5L, ((NoGuidRollingFlatFileTraceListener.TallyKeepingFileStreamWriter)traceListener.Writer).Tally);
			}
		}

		[TestMethod]
		public void RolledFileWillHaveCurrentDateForTimestamp()
		{
			using (NoGuidRollingFlatFileTraceListener traceListener
				= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
					maxInstances, throwMax, 10, "yyyy", NoGuidRollFileExistsBehavior.Overwrite, RollInterval.Day, 0))
			{
				traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;
				traceListener.Write("1234567890");

				Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

				traceListener.RollingHelper.PerformRoll(new DateTime(2007, 01, 01));
				traceListener.Write("12345");

				Assert.AreEqual(5L, ((NoGuidRollingFlatFileTraceListener.TallyKeepingFileStreamWriter)traceListener.Writer).Tally);
			}

			Assert.IsTrue(File.Exists(this.fileName));
			Assert.AreEqual("12345", File.ReadAllText(this.fileName));
			Assert.IsTrue(File.Exists(this.fileNameWithoutExtension + ".2007" + extension));
			Assert.AreEqual("1234567890", File.ReadAllText(this.fileNameWithoutExtension + ".2007" + extension));
		}

		[TestMethod]
		public void FallbackFileNameIsUsedForRoll()
		{
			using (FileStream fileStream = File.Open(this.fileName, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
			{
				using (NoGuidRollingFlatFileTraceListener traceListener
					= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
						2, throwMax, 10, "yyyy", NoGuidRollFileExistsBehavior.Overwrite, RollInterval.Day, 0))
				{
					traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;
					traceListener.Write("1234567890");

					Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

					traceListener.RollingHelper.PerformRoll(new DateTime(2007, 01, 01));
					traceListener.Write("12345");

					Assert.AreEqual(5L, ((NoGuidRollingFlatFileTraceListener.TallyKeepingFileStreamWriter)traceListener.Writer).Tally);
				}
			}
		}

		[TestMethod]
		public void RolledFileWithOverwriteWillOverwriteArchiveFileIfDateTemplateMatches()
		{
			using (NoGuidRollingFlatFileTraceListener traceListener
				= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
					maxInstances, throwMax, 0, "yyyy", NoGuidRollFileExistsBehavior.Overwrite, RollInterval.Day, 0))
			{
				traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;
				traceListener.Write("1234567890");

				Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

				traceListener.RollingHelper.PerformRoll(new DateTime(2007, 01, 01));
				traceListener.Write("12345");

				Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

				traceListener.RollingHelper.PerformRoll(new DateTime(2007, 01, 01));
				traceListener.Write("abcde");
			}

			Assert.IsTrue(File.Exists(this.fileName));
			Assert.AreEqual("abcde", File.ReadAllText(this.fileName));
			Assert.IsTrue(File.Exists(this.fileNameWithoutExtension + ".2007" + extension));
			Assert.AreEqual("12345", File.ReadAllText(this.fileNameWithoutExtension + ".2007" + extension));

			string[] archiveFiles = Directory.GetFiles(".", this.fileNameWithoutExtension + ".2007" + extension + "*");
			Assert.AreEqual(1, archiveFiles.Length);
		}

		[TestMethod]
		public void RolledFileWithOverwriteWillCreateArchiveFileIfDateTemplateDoesNotMatch()
		{
			using (NoGuidRollingFlatFileTraceListener traceListener
				= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
					maxInstances, throwMax, 0, "yyyy", NoGuidRollFileExistsBehavior.Overwrite, RollInterval.Day, 0))
			{
				traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;
				traceListener.Write("1234567890");

				Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

				traceListener.RollingHelper.PerformRoll(new DateTime(2007, 01, 01));
				traceListener.Write("12345");

				Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

				traceListener.RollingHelper.PerformRoll(new DateTime(2008, 01, 01));
				traceListener.Write("abcde");
			}

			Assert.IsTrue(File.Exists(this.fileName));
			Assert.AreEqual("abcde", File.ReadAllText(this.fileName));
			Assert.IsTrue(File.Exists(this.fileNameWithoutExtension + ".2008" + extension));
			Assert.AreEqual("12345", File.ReadAllText(this.fileNameWithoutExtension + ".2008" + extension));
			Assert.IsTrue(File.Exists(this.fileNameWithoutExtension + ".2007" + extension));
			Assert.AreEqual("1234567890", File.ReadAllText(this.fileNameWithoutExtension + ".2007" + extension));

			string[] archiveFiles = Directory.GetFiles(".", this.fileNameWithoutExtension + ".2007" + extension + "*");
			Assert.AreEqual(1, archiveFiles.Length);
			archiveFiles = Directory.GetFiles(".", this.fileNameWithoutExtension + ".2008" + extension + "*");
			Assert.AreEqual(1, archiveFiles.Length);
		}

		[TestMethod]
		public void RolledFileWithOverwriteWillFallBackToUniqueNameIfDateTemplateMatchesButArchiveFileIsInUse()
		{
			string targetArchiveFile = this.fileNameWithoutExtension + ".2007" + extension;

			using (FileStream stream = File.Open(targetArchiveFile, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
			{
				using (NoGuidRollingFlatFileTraceListener traceListener
					= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
						maxInstances, throwMax, 0, "yyyy", NoGuidRollFileExistsBehavior.Overwrite, RollInterval.Day, 0))
				{
					traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;
					traceListener.Write("1234567890");

					Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

					traceListener.RollingHelper.PerformRoll(new DateTime(2007, 01, 01));
					traceListener.Write("12345");
				}
			}

			Assert.IsTrue(File.Exists(this.fileName));
			Assert.AreEqual("12345", File.ReadAllText(this.fileName));
			Assert.IsTrue(File.Exists(targetArchiveFile));
			Assert.AreEqual("", File.ReadAllText(targetArchiveFile));	// couldn't archive

			string[] archiveFiles = Directory.GetFiles(".", targetArchiveFile + "*");
			Assert.AreEqual(2, archiveFiles.Length);
			foreach (string archiveFile in archiveFiles)
			{
				if (!Path.GetFileName(archiveFile).Equals(targetArchiveFile))
				{
					Assert.AreEqual("1234567890", File.ReadAllText(archiveFile));
				}
			}
		}

		[TestMethod]
		public void RolledFileWithIncrementWillCreateArchiveFileIfDateTemplateDoesNotMatch()
		{
			using (NoGuidRollingFlatFileTraceListener traceListener
				= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
					maxInstances, throwMax, 0, "yyyy", NoGuidRollFileExistsBehavior.Increment, RollInterval.Day, 0))
			{
				traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;
				traceListener.Write("1234567890");

				Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

				traceListener.RollingHelper.PerformRoll(new DateTime(2007, 01, 01));
				traceListener.Write("12345");

				Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

				traceListener.RollingHelper.PerformRoll(new DateTime(2008, 01, 01));
				traceListener.Write("abcde");
			}

			Assert.IsTrue(File.Exists(this.fileName));
			Assert.AreEqual("abcde", File.ReadAllText(this.fileName));
			Assert.IsTrue(File.Exists(this.fileNameWithoutExtension + ".2008.1" + extension));
			Assert.AreEqual("12345", File.ReadAllText(this.fileNameWithoutExtension + ".2008.1" + extension));
			Assert.IsTrue(File.Exists(this.fileNameWithoutExtension + ".2007.1" + extension));
			Assert.AreEqual("1234567890", File.ReadAllText(this.fileNameWithoutExtension + ".2007.1" + extension));

			string[] archiveFiles = Directory.GetFiles(".", this.fileNameWithoutExtension + ".2007*" + extension + "*");
			Assert.AreEqual(1, archiveFiles.Length);
			archiveFiles = Directory.GetFiles(".", this.fileNameWithoutExtension + ".2008*" + extension + "*");
			Assert.AreEqual(1, archiveFiles.Length);
		}

		[TestMethod]
		public void RolledFileWithIncrementWillCreateArchiveFileWithMaxSequenceIfDateTemplateDoesMatch()
		{
			using (NoGuidRollingFlatFileTraceListener traceListener
				= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
					maxInstances, throwMax, 0, "yyyy", NoGuidRollFileExistsBehavior.Increment, RollInterval.Day, 0))
			{
				traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;
				traceListener.Write("1234567890");

				Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

				traceListener.RollingHelper.PerformRoll(new DateTime(2007, 01, 01));
				traceListener.Write("12345");

				Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

				traceListener.RollingHelper.PerformRoll(new DateTime(2007, 01, 02));
				traceListener.Write("abcde");
			}

			Assert.IsTrue(File.Exists(this.fileName));
			Assert.AreEqual("abcde", File.ReadAllText(this.fileName));
			Assert.IsTrue(File.Exists(this.fileNameWithoutExtension + ".2007.2" + extension));
			Assert.AreEqual("12345", File.ReadAllText(this.fileNameWithoutExtension + ".2007.2" + extension));
			Assert.IsTrue(File.Exists(this.fileNameWithoutExtension + ".2007.1" + extension));
			Assert.AreEqual("1234567890", File.ReadAllText(this.fileNameWithoutExtension + ".2007.1" + extension));

			string[] archiveFiles = Directory.GetFiles(".", this.fileNameWithoutExtension + ".2007*" + extension + "*");
			Assert.AreEqual(2, archiveFiles.Length);
		}

		[TestMethod]
		public void WillRollForDateIfEnabled()
		{
			using (NoGuidRollingFlatFileTraceListener traceListener
				= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
					maxInstances, throwMax, 0, "yyyy", NoGuidRollFileExistsBehavior.Increment, RollInterval.Day, 0))
			{
				traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;

				this.dateTimeProvider.currentDateTime = DateTime.Now;
				traceListener.RollingHelper.UpdateRollingInformationIfNecessary();

				this.dateTimeProvider.currentDateTime = DateTime.Now.AddDays(2);
				Assert.IsNotNull(traceListener.RollingHelper.CheckIsRollNecessary());
			}

			using (NoGuidRollingFlatFileTraceListener traceListener
				= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
					maxInstances, throwMax, 0, "yyyy", NoGuidRollFileExistsBehavior.Increment, RollInterval.None, 0))
			{
				traceListener.RollingHelper.UpdateRollingInformationIfNecessary();

				traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;

				this.dateTimeProvider.currentDateTime = DateTime.Now;
				traceListener.RollingHelper.UpdateRollingInformationIfNecessary();

				this.dateTimeProvider.currentDateTime = DateTime.Now.AddDays(2);
				Assert.IsNull(traceListener.RollingHelper.CheckIsRollNecessary());
			}
		}

		[TestMethod]
		public void WillRollForSize()
		{
			using (NoGuidRollingFlatFileTraceListener traceListener
				= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
					maxInstances, throwMax, 1, "yyyy", NoGuidRollFileExistsBehavior.Increment, RollInterval.Year, 0))
			{
				traceListener.RollingHelper.UpdateRollingInformationIfNecessary();

				traceListener.Write(new string('c', 1200));

				Assert.IsNotNull(traceListener.RollingHelper.CheckIsRollNecessary());
			}

			using (NoGuidRollingFlatFileTraceListener traceListener
				= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
					maxInstances, throwMax, 0, "yyyy", NoGuidRollFileExistsBehavior.Increment, RollInterval.Year, 0))
			{
				traceListener.RollingHelper.UpdateRollingInformationIfNecessary();

				traceListener.Write(new string('c', 1200));

				Assert.IsNull(traceListener.RollingHelper.CheckIsRollNecessary());
			}
		}

        [TestMethod]
        public void AllowRollingForSizeWhenBehaviorIsIncrementAndTimestampIsEmpty()
        {
            using (NoGuidRollingFlatFileTraceListener traceListener
                = new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
					maxInstances, throwMax, 1, string.Empty, NoGuidRollFileExistsBehavior.Increment, RollInterval.None, 0))
            {
                traceListener.Write(new string('c', 1025));

                traceListener.TraceData(new System.Diagnostics.TraceEventCache(),
                    "source",
                    System.Diagnostics.TraceEventType.Error,
                    0,
                    "logged message");
            }
            string[] wroteFiles = Directory.GetFiles(".", fileNameWithoutExtension + "*");
            Assert.AreEqual(2, wroteFiles.Length);
        }

		[TestMethod]
		public void AllowRevolvingForSizeWhenBehaviorIsIncrementAndTimestampIsEmpty()
		{
			using (NoGuidRollingFlatFileTraceListener traceListener
				= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
					maxInstances, throwMax, 1, string.Empty, NoGuidRollFileExistsBehavior.Revolving, RollInterval.None, 0)) {
				traceListener.Write(new string('0', 1025));
				AssertRevolvingWrite(traceListener, '1'); AssertRevolvingRead(1, '0');
				AssertRevolvingWrite(traceListener, '2'); AssertRevolvingRead(1, '1');
				AssertRevolvingWrite(traceListener, '3'); AssertRevolvingRead(1, '2');
			}
			using (NoGuidRollingFlatFileTraceListener traceListener
				= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
					maxInstances, throwMax, 1, string.Empty, NoGuidRollFileExistsBehavior.Revolving, RollInterval.None, 1)) {
				AssertRevolvingWrite(traceListener, '4'); AssertRevolvingRead(2, '3');
				AssertRevolvingWrite(traceListener, '5'); AssertRevolvingRead(3, '4');
				AssertRevolvingWrite(traceListener, '6'); AssertRevolvingRead(4, '5');
			}
			string[] wroteFiles = Directory.GetFiles(".", fileNameWithoutExtension + "*");
			Assert.AreEqual(5, wroteFiles.Length);
		}
		private void AssertRevolvingWrite(NoGuidRollingFlatFileTraceListener traceListener, char cWrite)
		{
			traceListener.TraceData(new System.Diagnostics.TraceEventCache(),
				"source",
				System.Diagnostics.TraceEventType.Error,
				0,
				"logged message");
			string sWrite = new string(cWrite, 1025);
			traceListener.Write(sWrite);
			Assert.IsTrue(File.Exists(this.fileName));
		}
		private void AssertRevolvingRead(int iRead, char cRead)
		{
			string sRead = new string(cRead, 1025);
			string fRead = this.fileNameWithoutExtension + '.' + iRead + extension;
			Assert.IsTrue(File.Exists(fRead));
			string fileText = File.ReadAllText(fRead);
			Assert.IsTrue(fileText.Contains(sRead));
		}

		[TestMethod]
		public void FindsLastSequenceOnFiles()
		{
			for (int i = 0; i < 15; i++)
			{
				if (i % 2 == 0 || i % 3 == 0)
				{
					string tempfilename = this.fileNameWithoutExtension + "." + i + extension;
					File.WriteAllText(tempfilename, "some text");
				}
			}

			int maxSequenceNumber
				= NoGuidRollingFlatFileTraceListener.StreamWriterRollingHelper.FindMaxSequenceNumber(".",
					this.fileNameWithoutExtension,
					extension);

			Assert.AreEqual(14, maxSequenceNumber);
		}

		[TestMethod]
		public void WillNotRollWhenTracingIfNotOverThresholds()
		{
			using (NoGuidRollingFlatFileTraceListener traceListener
				= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
					maxInstances, throwMax, 0, "yyyy", NoGuidRollFileExistsBehavior.Increment, RollInterval.Day, 0))
			{
				traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;
			}
		}

		[TestMethod]
		public void WillRollExistingFileIfOverSizeThreshold()
		{
			string existingPayload = new string('c', 5000);
			DateTime currentDateTime = new DateTime(2007, 1, 1);
			File.WriteAllText(this.fileName, existingPayload);
			File.SetCreationTime(this.fileName, currentDateTime);

			using (NoGuidRollingFlatFileTraceListener traceListener
				= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
					maxInstances, throwMax, 1, "yyyy", NoGuidRollFileExistsBehavior.Overwrite, RollInterval.None, 0))
			{
				traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;
				this.dateTimeProvider.currentDateTime = currentDateTime;

				traceListener.TraceData(new System.Diagnostics.TraceEventCache(),
					"source",
					System.Diagnostics.TraceEventType.Error,
					0,
					"logged message");
			}

			Assert.AreEqual(existingPayload, File.ReadAllText(this.fileNameWithoutExtension + ".2007" + extension));
			Assert.IsTrue(File.ReadAllText(this.fileName).Contains("logged message"));
		}

		[TestMethod]
		public void WillRollExistingFileIfOverDateThreshold()
		{
			string existingPayload = new string('c', 10);
			DateTime currentDateTime = new DateTime(2007, 1, 1);
			File.WriteAllText(this.fileName, existingPayload);
			File.SetCreationTime(this.fileName, currentDateTime);

			using (NoGuidRollingFlatFileTraceListener traceListener
				= new NoGuidRollingFlatFileTraceListener(fileName, "header", "footer", null,
					maxInstances, throwMax, 1, "yyyy", NoGuidRollFileExistsBehavior.Overwrite, RollInterval.Day, 0))
			{
				traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;
				this.dateTimeProvider.currentDateTime = currentDateTime.AddDays(2);

				traceListener.TraceData(new System.Diagnostics.TraceEventCache(),
					"source",
					System.Diagnostics.TraceEventType.Error,
					0,
					"logged message");
			}

			Assert.AreEqual(existingPayload, File.ReadAllText(this.fileNameWithoutExtension + ".2007" + extension));
			Assert.IsTrue(File.ReadAllText(this.fileName).Contains("logged message"));
		}

        private class MockDateTimeProvider : NoGuidRollingFlatFileTraceListener.DateTimeProvider
        {
            public DateTime? currentDateTime = null;

            public override DateTime CurrentDateTime
            {
                get
                {
                    if (currentDateTime != null)
                        return currentDateTime.Value;

                    return base.CurrentDateTime;
                }
            }
        }
	}
}